package com.ycsj.goldmedalnewconcept.common.fragment;

import android.Manifest;
import android.app.Service;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.ycsj.common.base.BaseLazyFragment;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.MediaPlayerManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.activity.AnswerListDetailsActivity;
import com.ycsj.goldmedalnewconcept.common.activity.FollowReadDetailsActivity;
import com.ycsj.goldmedalnewconcept.common.adapter.FollowLvAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.AnswerInfo;
import com.ycsj.goldmedalnewconcept.common.bean.ChooseItem;
import com.ycsj.goldmedalnewconcept.common.bean.TopicInfo;
import com.ycsj.goldmedalnewconcept.common.iflytek.Result;
import com.ycsj.goldmedalnewconcept.common.iflytek.XmlResultParser;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 课文跟读的Framgent
 * Created by Administrator on 2019/4/4 0004.
 */

public class AnswerFragment extends BaseLazyFragment {

    @BindView(R.id.ll_top_lb)
    LinearLayout llTopLb;
    @BindView(R.id.lv_top_laba)
    ImageView lvPlay;
    @BindView(R.id.tv_topic)
    TextView tvTopic;
    @BindView(R.id.lv)
    ListView lv;
    @BindView(R.id.lv_replay)
    ImageView lvReplay;
    @BindView(R.id.lv_record)
    ImageView lvRecord;
    @BindView(R.id.ll_loading)
    LinearLayout llLoading;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.ll_botttom)
    LinearLayout llBottom;


    //页面的问题对象
    private TopicInfo.QuestionListBean info;

    //当前小题所在大题中的位置
    private int pos;

    //总的题目数量
    private int totalSize;

    //lessonId
    private String lessonId;

    //单元号
    private String unit;

    //是否是最后页面的标识
    private boolean isLastPage;

    //音频的地址
    private String audio;

    //索引的集合
    private String[] indexs = {"A", "B", "C", "D", "E"};

    //当前题目的正确答案
    private String rightAnswer;

    //展示选项的列表适配器
    private FollowLvAdapter adapter;

    //顶部播放句子音频的帧动画对象
    private AnimationDrawable lvTopAnim;


    //用于控制是否有录音文件的标识
    private boolean hasRecord;

    /**
     * 录音的弹框PopUpWinow相关
     */
    private View view;
    private ImageView lvPopRecord;
    private PopupWindow popupWindow;
    private AnimationDrawable popAnimationDrawable;

    // 控制松手是否显示加载框的标记
    private boolean isShowDialog = true;

    // 讯飞SDK对象
    private SpeechEvaluator mSpeechEvaluator;

    //控制录音次数
    private int recordCount;

    //录音权限
    private String[] permissions = {Manifest.permission.RECORD_AUDIO,};


    //是否按下了
    private boolean hasActionDown = false;

    /**
     * 对外提供的生成该类对象的方法,不可单例
     *
     * @param info      页面的数据对象
     * @param pos       当前小题在大题中的位置
     * @param totalSize 总的题目数
     * @param lessionId LessonId
     * @return
     */
    public static AnswerFragment newInstance(TopicInfo.QuestionListBean info, int pos,
                                             int totalSize, String lessionId, boolean isLastPage, String unit) {

        AnswerFragment answerFragment = new AnswerFragment();
        // 通过arguments携带页面数据
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        bundle.putInt("position", pos);
        bundle.putInt("totalSize", totalSize);
        bundle.putString("lessionId", lessionId);
        bundle.putBoolean("isLastPage", isLastPage);
        bundle.putString("unit", unit);
        answerFragment.setArguments(bundle);
        return answerFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_answer;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);

        //获取数据
        initIntent();

        //配置科大讯飞的参数
        setParams();

        //设置数据
        setPageDate();

        //设置录音的触摸事件
        initTouchListener();
    }


    /**
     * 获取数据
     */
    private void initIntent() {
        info = (TopicInfo.QuestionListBean) getArguments().getSerializable("data");
        pos = getArguments().getInt("position");
        totalSize = getArguments().getInt("totalSize");
        lessonId = getArguments().getString("lessionId");
        isLastPage = getArguments().getBoolean("isLastPage");
        unit = getArguments().getString("unit");
    }

    /**
     * 设置数据
     */
    private void setPageDate() {
        if (info == null) {
            return;
        } else {
            //设置底部TextView的数据
            if (isLastPage) {
                //是最后一页
                btNext.setText("最后一题");
            } else {
                btNext.setText("下一题");
            }

            //当前题目的正确答案
            rightAnswer = info.getQuestion_answer();

            // 记录当前题目播放的音频地址
            audio = info.getAudio();

            // 设置题目信息
            // 获取题目内容
            String questionContent = info.getQuestion_content();

            // 将其中的"填空"用下划线取代
            String newContent = questionContent.replaceAll("填空", "___");
            tvTopic.setText(newContent);

            //组装答案选项的集合
            List<TopicInfo.QuestionListBean.DetailListBean> chooseAnswers = info.getDetail_list();
            if (chooseAnswers != null && chooseAnswers.size() != 0) {
                //创建选项的集合
                List<ChooseItem> items = new ArrayList<>();
                for (int i = 0; i < chooseAnswers.size(); i++) {
                    ChooseItem item = new ChooseItem();
                    item.content = chooseAnswers.get(i).getDetail_content();
                    item.isChoosed = false;
                    if (rightAnswer.equals(chooseAnswers.get(i).getDetail_content())) {
                        //该选项正确
                        item.isRight = true;
                    } else {
                        item.isRight = false;
                    }

                    //赋值选项索引
                    item.index = indexs[i];

                    items.add(item);
                }

                //初始化展示答案列表
                initLv(items);
            }
        }
    }


    /**
     * 设置讯飞语音录制对象的参数方法
     */
    private void setParams() {

        mSpeechEvaluator = SpeechEvaluator.createEvaluator(getActivity(), null);

        // 设置评测语种
        mSpeechEvaluator.setParameter(SpeechConstant.LANGUAGE, "en_us");

        // 设置评测题型
        // mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
        // "read_word");//单词

        mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
                "read_sentence");// 句子

        // 设置试题编码类型
        mSpeechEvaluator.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");

        // 设置前、后端点超时
        mSpeechEvaluator.setParameter(SpeechConstant.VAD_BOS, "3000");
        mSpeechEvaluator.setParameter(SpeechConstant.VAD_EOS, "1800");

        // 设置录音超时，设置成-1 则无超时限制
        mSpeechEvaluator.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");

        // 设置结果等级，不同等级对应不同的详细程度
        mSpeechEvaluator.setParameter(SpeechConstant.RESULT_LEVEL, "complete");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mSpeechEvaluator.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

        // 配置录音文件存放的位置
        // mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
        // Environment.getExternalStorageDirectory().getAbsolutePath()
        // + "/msc/" + "ice" + postion + ".wav");

    }

    /**
     * 初始化选项列表的ListView
     *
     * @param items
     */
    private void initLv(final List<ChooseItem> items) {
        // LogUtils.iTag("test",GsonUtil.listToJson(items));
        adapter = new FollowLvAdapter(getContext(), items, R.layout.lv_follow_read);
        lv.setAdapter(adapter);

        //条目点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {

                if (!items.get(pos).isChoosed) {
                    if (items.get(pos).isRight) {
                        //播放正确的音乐
                        playChooseAnserAudio(R.raw.rightmp3);

                        //将顶部的播放音频的喇叭和底部的录音按钮进行显示
                        llTopLb.setVisibility(View.VISIBLE);

                        llBottom.setVisibility(View.VISIBLE);

                        //该选项是正确的选择后将全部选项展示
                        for (int i = 0; i < items.size(); i++) {
                            items.get(i).isChoosed = true;
                        }

                        //选择正确后
                        setRedAnswer(info.getDialogue(), items.get(pos).content);

                    } else {
                        //播放错误的音乐
                        playChooseAnserAudio(R.raw.errormp3);

                        //如果该选项是错误的则只改变当前选项的状态
                        items.get(pos).isChoosed = !items.get(pos).isChoosed;
                    }

                    adapter.notifyDataSetChanged();
                }

            }
        });
    }


    // 检查是否已授权
    private boolean checkPermission(String permissionName) {
        return PermissionX.isGranted(getContext(), permissionName);
    }

    //申请权限
    private void applyPermission() {

        PermissionX.init(this)
                .permissions(permissions)
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                        if (allGranted) {
//                            LogUtils.iTag("test", "申请权限了");
                        } else {
//                            LogUtils.iTag("test", "拒绝权限了");
                            Toast.makeText(getActivity(), "录音权限未通过，录音功能无法使用", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    /**
     * 设置录音的触摸事件
     */
    private void initTouchListener() {
        lvRecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:


                        //先进行权限的判定,如果没有权限就去申请权限,有权限在进行录音操作
                        if (checkPermission(Manifest.permission.RECORD_AUDIO)) {

                            if (recordCount < 2) {
                                // 按下的时候重置状态
                                isShowDialog = true;

                                // 隐藏加载显示分数,下一步按钮
                                llLoading.setVisibility(View.INVISIBLE);
                                tvScore.setVisibility(View.INVISIBLE);

                                // 按下的操作
                                showRecordPop();

                                // 同时开始录音并播放
                                doRecordAction();
                            } else {
                                ToastUtils.showShort("最多只能进行2次评测");
                            }

                        } else {
                            //没有录音权限,申请录音权限
                            applyPermission();
                        }

                        break;

                    case MotionEvent.ACTION_UP:

                        if (hasActionDown) {

                            // 松下的操作
                            if (null != popupWindow && popupWindow.isShowing()) {
                                popupWindow.dismiss();
                            }

                            // 松手的时候开始加载框转圈功能
                            if (null != llLoading) {
                                if (isShowDialog) {
                                    llLoading.setVisibility(View.VISIBLE);
                                } else {
                                    llLoading.setVisibility(View.INVISIBLE);
                                }
                            }
                            //还原按下状态
                            hasActionDown = false;
                        }
                }

                return true;
            }
        });
    }

    /**
     * 语音评测的方法
     */
    private void doRecordAction() {

        //记录录音的次数
//        recordCount++;

        // 清空播放器的播放状态
        MediaPlayerManager.getInstance().stop();

        // 设置顶部喇叭的图片
        if (lvTopAnim != null && lvTopAnim.isRunning()) {
            lvTopAnim.stop();
            lvTopAnim = null;
        }
        lvPlay.setImageResource(R.drawable.st_voice_anim);

        // 恢复底部的播放按钮的状态
        lvReplay.setImageResource(R.drawable.playcloze);

        // 震动手机
        Vibrator vibrator = (Vibrator) getActivity().getSystemService(
                Service.VIBRATOR_SERVICE);
        vibrator.vibrate(500);

        if (mSpeechEvaluator == null) {
            return;
        }

        // 重新配置讯飞的录音存放位置
//        mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
//                Environment.getExternalStorageDirectory().getAbsolutePath()
//                        + "/msc/" + "ice" + pos + ".wav");

        mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
                getAmrPath(pos));

        // 开启评测功能
        mSpeechEvaluator.startEvaluating(info.getSpeechtest(), null,
                new EvaluatorListener() {

                    // volume音量值0~30，data音频数据
                    @Override
                    public void onVolumeChanged(int volume, byte[] data) {

                    }

                    // 结果回调，评测过程中可能会多次调用该方法，isLast为true则为最后结果
                    @SuppressWarnings({"static-access", "static-access"})
                    @Override
                    public void onResult(EvaluatorResult result, boolean isLast) {

                        if (isLast) {

                            StringBuilder builder = new StringBuilder();
                            builder.append(result.getResultString());

                            XmlResultParser resultParser = new XmlResultParser();

                            Result result1 = resultParser.parse(result
                                    .getResultString());

                            // 处理乱读的问题
                            if (!TextUtils.isEmpty(builder)) {
                                if (!result1.is_rejected) {
                                    float a = result1.total_score;
                                    float b = (float) (Math.round(a * 10)) / 10;
                                    isShowDialog = false;

                                    // 更改录音文件状态证明已经录音
                                    hasRecord = true;

                                    if (null != popupWindow
                                            && popupWindow.isShowing()) {
                                        popupWindow.dismiss();
                                    }

                                    llLoading.setVisibility(View.INVISIBLE);
                                    tvScore.setVisibility(View.VISIBLE);
                                    tvScore.setText(b + " 分");

                                    // 更新集合中保存的对应位置的AnswerInfo
                                    String answerJson = SPUtil.getString(getActivity(), lessonId);

                                    if (!TextUtils.isEmpty(answerJson)) {
                                        // 更新对应位置的Bean信息
                                        List<AnswerInfo> answerDatas = GsonUtil
                                                .jsonToList(answerJson,
                                                        AnswerInfo[].class);

                                        AnswerInfo answerInfo = answerDatas
                                                .get(pos);
                                        answerInfo.score = b;
                                        answerInfo.audioPath = getAmrPath(pos);

                                        // 更新Info的播放文件
                                        info.setAudio(getAmrPath(pos));

                                        // 更新Sp中保存的值
                                        SPUtil.put(getContext(), lessonId, GsonUtil.listToJson(answerDatas));
                                    }

                                    // 显示评分按钮后将下一步按钮显示出来
                                    btNext.setVisibility(View.VISIBLE);

                                    // 播放科大讯飞的评分语音
                                    int resId = -1;
                                    if (b < 1.0) {
                                        resId = R.raw.musicrecord1;
                                    } else if (b >= 1.0 && b < 2.0) {
                                        resId = R.raw.musicrecord2;
                                    } else if (b >= 2.0 && b < 3.0) {
                                        resId = R.raw.musicrecord3;
                                    } else if (b >= 3.0 && b < 4.0) {
                                        resId = R.raw.musicrecord4;
                                    } else if (b >= 4.0 && b <= 5.0) {
                                        resId = R.raw.musicrecord5;
                                    }

                                    MediaPlayerManager.getInstance().playLocalFile(resId, null, null);
                                } else {

                                    //乱读或未读
                                    isShowDialog = false;

                                    // 更改录音文件状态证明已经录音
                                    hasRecord = false;

                                    if (null != popupWindow
                                            && popupWindow.isShowing()) {
                                        popupWindow.dismiss();
                                    }

                                    llLoading.setVisibility(View.INVISIBLE);
                                    tvScore.setVisibility(View.VISIBLE);
                                    tvScore.setText("0.0 分");
                                    ToastUtils.showShort("未检测到录音或者乱读,请重新录音");

                                }

                            }
                        }
                    }

                    // 扩展接口，暂时没有回调
                    @Override
                    public void onEvent(int arg0, int arg1, int arg2,
                                        Bundle arg3) {

                    }

                    // 出错回调
                    @Override
                    public void onError(SpeechError error) {

                        LogUtils.iTag("test", "走了错误了");
                        isShowDialog = false;

                        if (null != popupWindow && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }

                        if (null != llLoading) {
                            llLoading.setVisibility(View.INVISIBLE);
                        }

                        if (null != tvScore) {
                            tvScore.setVisibility(View.INVISIBLE);
                        }

                        if (null != btNext) {
                            btNext.setVisibility(View.INVISIBLE);
                        }

                        ToastUtils.showShort("评测异常,请重新录音");
                    }

                    // 说话结束回调
                    @Override
                    public void onEndOfSpeech() {
                    }

                    // 开始说话回调
                    @Override
                    public void onBeginOfSpeech() {

                    }
                });
    }


    /**
     * 弹出录音的PopUpwindow
     */
    private void showRecordPop() {

        view = View.inflate(getActivity(), R.layout.st_pop_record, null);

        lvPopRecord = view.findViewById(R.id.lv_pop_record);

        // 给顶部的图片设置帧动画
        lvPopRecord.setImageResource(R.drawable.st_record_anim);

        // 获取帧动画对象
        popAnimationDrawable = (AnimationDrawable) lvPopRecord.getDrawable();

        // 开启帧动画
        popAnimationDrawable.start();

        popupWindow = new PopupWindow(view,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                if (null != popAnimationDrawable) {
                    popAnimationDrawable.stop();
                }
            }
        });
        popupWindow.showAtLocation(getActivity().getWindow().getDecorView(),
                Gravity.CENTER, 0, 0);
    }

    /**
     * 选择后播放录音的方法
     *
     * @param resId
     */
    private void playChooseAnserAudio(int resId) {
        MediaPlayerManager.getInstance().playLocalFile(resId, new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                MediaPlayerManager.getInstance().stop();
            }
        }, new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                MediaPlayerManager.getInstance().stop();
                return false;
            }
        });
    }


    /**
     * 播放句子音频的方法
     */
    private void playSentenceAudio() {
        // 获取帧动画对象
        lvTopAnim = (AnimationDrawable) lvPlay.getDrawable();

        //开启帧动画
        lvTopAnim.start();

        //将底部的播放录音的按钮状态还原
        lvReplay.setImageResource(R.drawable.playcloze);

        MediaPlayerManager.getInstance().play(audio, new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                MediaPlayerManager.getInstance().stop();
                lvPlay.setImageResource(R.drawable.st_voice_anim);
            }
        }, new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                MediaPlayerManager.getInstance().stop();
                lvPlay.setImageResource(R.drawable.st_voice_anim);
                return false;
            }
        });
    }


    /**
     * 播放录音音频
     */
    private void doPlayRecordAudio() {

//        LogUtils.iTag("test", "是否有录音的控制值是:" + hasRecord);

        if (hasRecord) {
            String recordPath = getAmrPath(pos);
            LogUtils.iTag("test", "录音地址是" + recordPath);

            //重置顶部的播放句子音频的状态
            if (lvTopAnim != null && lvTopAnim.isRunning()) {
                lvTopAnim.stop();
            }
            lvPlay.setImageResource(R.drawable.st_voice_anim);

            //改变播放录音按钮的状态
            lvReplay.setImageResource(R.drawable.stopcloze);

            //播放音频
            MediaPlayerManager.getInstance().playSdCardFile(getContext(), getAmrPath(pos), null, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    MediaPlayerManager.getInstance().stop();
                    lvReplay.setImageResource(R.drawable.playcloze);
                }
            }, new MediaPlayer.OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    LogUtils.iTag("test", "播放报错", i);
                    MediaPlayerManager.getInstance().stop();
                    lvReplay.setImageResource(R.drawable.playcloze);
                    return false;
                }
            });

        } else {
//            ToastUtils.showShort("请先录音");
            com.ycsj.common.toast.ToastUtils.show("请先录音");
        }
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.lv_top_laba, R.id.lv_replay, R.id.bt_next})
    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.lv_top_laba:
                //播放音频
                playSentenceAudio();
                break;
            case R.id.lv_replay:
                //播放录音
                doPlayRecordAudio();
                break;
            case R.id.bt_next:
                //下一题
                doNextAction();
                break;
        }
    }


    /**
     * 点击下一题的点击事件
     */
    private void doNextAction() {
        if (pos != totalSize - 1) {
            // 不是最后一页,就发送广播
            // 发送一个广播通知FollowReadDetailsActivity去进行ViewPager的翻页处理
            BusInfo busInfo = new BusInfo();
            busInfo.type = FollowReadDetailsActivity.VPSCROLL;
            EventBus.getDefault().post(busInfo);

            //将播放器的状态清空
            if (lvTopAnim != null && lvTopAnim.isRunning()) {
                lvTopAnim.stop();
                lvTopAnim = null;
                lvPlay.setImageResource(R.drawable.st_voice_anim);
            }

            lvReplay.setImageResource(R.drawable.playcloze);

            MediaPlayerManager.getInstance().stop();

        } else {

            //请求生成牛奶的接口
            //课文跟读  source来源编号是3,moduleid模块编号是9,score为空
//            MilkUtils.getMilk(getContext(), AccountUtils.getTeacher(getContext()), AccountUtils.getClassNum(getContext()), "3", unit, "9", "");

            // 跳转到详情页面
            AnswerListDetailsActivity.goActivity(getContext(), lessonId, "0");
        }

    }


    /**
     * 根据当前页面获取录音文件的路径的方法
     *
     * @return
     */
    private String getAmrPath(int postion) {
//        File file = new File(Environment.getExternalStorageDirectory()
//                .getAbsolutePath() + "/msc/" + "ice" + postion + ".wav");
//        return file.getAbsolutePath();

        File file = new File(Objects.requireNonNull(getContext()).getCacheDir(), "/msc/" + "ice" + postion + ".wav");
        return file.getAbsolutePath();
    }


    /**
     * 回显答案并且进行红色显示的方法
     *
     * @param newContent
     * @param answer
     */
    private void setRedAnswer(String newContent, String answer) {

        // 对答案进行;切割
        String[] answers = answer.split(";");
        SpannableStringBuilder spannable = new SpannableStringBuilder(
                newContent);

        // 获取切割的字符串在题目中的位置
        for (int i = 0; i < answers.length; i++) {

            int startIndex = newContent.indexOf(answers[i]);

            int endIndex = startIndex + answers[i].length();

            try {
                spannable.setSpan(new ForegroundColorSpan(Color.RED), startIndex,
                        endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } catch (Exception e) {
                Log.e("error", e.toString());
            }
        }

        tvTopic.setText(spannable);
    }


}
